// 获取应用实例
const app = getApp()
import {
    newExportWorkerList,
    deleteWorker,
    cancelInsure,
    getInsurancePdf,
    addToProjectFromBook,
    confirmInsure,
    getAccountExpireNotify
} from '../../../api/app.js'
import {
    setProjectClockTime,
    setProjectClockAddress,
    updateAgeRange,
    getPayDetailInfo,
    getPayDetailList
} from '../../api/pay'


import {
    inputchange,
    toast,
    confirm,
    openDocument,
    getLocation,
    shake
} from '../../../utils/util.js'
import user from '../../../utils/user.js'
import Socket from '../../../api/socket.js'
const toastHistory = []

Page({
    data: {
        isPopupPay: false,
        top: app.globalData.menuTop,
        workers: [],
        date: '',
        companyName: '',
        companyId: '',
        recipient: '',
        projectName: '',
        projectNum: '',
        women: 0,
        men: 0,
        workerCount: 0,
        morePosition: 0,
        showMoreStatus: false,
        projectId: 0,
        showGodAddStatus: false,
        invitationStatus: false,
        copyLinkStatus: false,
        copyLinkContent: '',
        isOld: false,
        clockStartTime: '',
        clockEndTime: '',
        clockAddress: '',
        staffUnderpay: 0,
        setStaffUnderpayStatus: false,
        dayNightFlag: 0,
        signInMode: 0,
        signInType: '',
        isOpenWesure: false,
        wesureIsDelete: false,
        isTipInsurance: false,
        tipTop: 0,
        ageSection: '',
        ageStart: '',
        ageEnd: '',
        ageArr: [],
        ageUnit: true,
        ispopupRemind: false,
        requestType: ''
    },
    onLoad(options) {
        user.waitLogin().then(() => {
            console.log(options, 'options')
            console.log('onLoad调用啦吗')
            this.setData({
                projectId: options.id,
                requestType: options.type,
                socket: new Socket('/api/v2/webSocket/' + options.id + '/' + user.userId, (message) => {
                    try {
                        const data = JSON.parse(message.data)
                        console.log('data111', data)
                        switch (data.type) {
                            case 'add': // 人员加入
                                for (const item in this.data.workers) { // 防止刷新后的重复加入
                                    if (data.data.id === item.id) {
                                        return
                                    }
                                }
                                data.data.userName = data.data.workerName
                                data.data.workerName = data.data.workerName + '（' + data.data.idCardNo.slice(-4) + '）'
                                data.data.showAll = false
                                data.data.key = data.data.id
                                this.data.workers.unshift(data.data)
                                console.log(this.data.workers, 'this.data.workers')
                                let manNum = 0
                                let womanNum = 0
                                this.data.workers.forEach((ele)=>{
                                    if (ele.sex==='0') {
                                        manNum += 1
                                    }
                                    if (ele.sex==='1') {
                                        womanNum += 1
                                    }
                                })
                                this.setData({
                                    workers: this.data.workers,
                                    workerCount: this.data.workerCount + 1,
                                    men: manNum,
                                    women: womanNum,
                                })
                                break
                            case 'modify': // 状态更新
                                this.data.workers.forEach((item, index) => {
                                    if (item.userId === data.data.userId) {
                                        this.setData({
                                            ['workers[' + index + '].policyStatus']: data.data.insuredStatusCn,
                                            ['workers[' + index + '].expiredTime']: data.data.expiredTime,
                                            ['workers[' + index + '].key']: this.data.workers[index].id + '' + data.data.insuredStatusCn,
                                        })
                                        return
                                    }
                                })
                                break
                            case 'delete': // 有员工被删除
                                this.data.workers.forEach((item, index) => {
                                    if (item.userId === data.data.userId) {
                                        this.data.workers.splice(index, 1)
                                        console.log(this.data.workers, 'this.data.workers')
                                        let manNum = 0
                                        let womanNum = 0
                                        this.data.workers.forEach((ele)=>{
                                            if (ele.sex==='0') {
                                                manNum += 1
                                            }
                                            if (ele.sex==='1') {
                                                womanNum += 1
                                            }
                                        })
                                        this.setData({
                                            workers: this.data.workers,
                                            workerCount: this.data.workerCount - 1,
                                            men: manNum,
                                            women: womanNum,
                                        })
                                        return
                                    }
                                })
                                break
                            case 'update':
                                console.log('触发更新')
                                this.data.workers.forEach((item, index) => {
                                    if (item.id === data.data.id) {
                                        this.setData({
                                            ['workers[' + index + '].remark']: data.data.remark
                                        })
                                        return
                                    }
                                })
                                console.log(this.data.workers, 'workersworkers')
                                break
                            case 'exception':
                                if (toastHistory.indexOf(data.data.msg) === -1)
                                    app.alert(data.data.msg)
                                break
                        }
                    } catch (e) {
                        // 非JSON请求
                        console.log(message.data)
                    }
                })
            })
            this.getProject()
            this.getProjectWorker()
            const ageArr = [
                ['不限制'],
                ['不限制']
            ]
            for (let i = 14; i <= 80; i++) {
                ageArr[0].push(i)
            }
            ageArr[1] = ageArr[0]
            this.setData({
                ageArr: ageArr
            })
        })
    },
    static: {
        pageNum: 1,
        notPage: false,
        searchValue: ''
    },
    onShow() {
        // this.getProjectWorker()
    },
    onUnload() {
        this.data.socket.close()
    },
    // 选择年龄范围开始
    onChoiceAge(event) {
        const {
            value
        } = event.detail
        if (value[0] !== 0 && value[1] !== 0) {
            if (value[0] > value[1]) {
                app.toast('起始年龄不可大于结束年龄')
                return
            }
            if (value[1] < value[0]) {
                app.toast('结束年龄不可小于开始年龄')
                return
            }
        }
        const {
            ageArr
        } = this.data
        console.log(event, 'event')
        // 显示在页面的内容
        this.setData({
            ageSection: value[0] == 0 ? '不限制' + '-' + ageArr[1][value[1]] : value[1] == 0 ? ageArr[0][value[0]] + '-' + '不限制' : (!value[0] && !value[1]) ? '不限制-不限制' : ageArr[0][value[0]] + '-' + ageArr[1][value[1]],
            ageUnit: value[1] == 0 ? false : true
        })
        // 传给后端的内容
        const ageSection = (!value[0] && !value[1]) ? '~-~' : value[0] == 0 ? '~' + '-' + ageArr[1][value[1]] : value[1] == 0 ? ageArr[0][value[0]] + '-' + '~' : ageArr[0][value[0]] + '-' + ageArr[1][value[1]]
        updateAgeRange({
            id: this.data.projectId,
            ageRange: ageSection,

        }).then(res => {
            app.toast('修改成功')
        })
    },

    getProject() {
        getPayDetailInfo({
            id: this.data.projectId
        }).then((res) => {
            // 判断是否为当天之前的项目
            const isOld = new Date(res.createTime).getTime() < new Date(new Date().toLocaleDateString()).getTime()
            this.setData({
                date: res.date,
                companyName: res.serveCompanyName,
                companyId: res.serveCompanyId,
                projectName: res.projectName,
                projectNum: res.projectNum,
                recipient: res.recipient,
                type: res.type,
                clockStartTime: res.signTimeStart,
                clockEndTime: res.signTimeEnd,
                clockAddress: res.signPlace,
                staffUnderpay: res.staffUnderpay,
                setStaffUnderpay: '',
                isOld,
                dayNightFlag: res.dayNightFlag,
                signInType: res.signInType,
                isOpenWesure: res.isOpenWesure,
                wesureIsDelete: res.serverCompanyIsDelete,
                wesureTypeName: res.wesureTypeName,
                wesureInfo: res.wesureInfo,
                signInMode: res.signInMode,
                ageSection: res.ageRange ? ((res.ageRange.split('-')[0] == '~' && res.ageRange.split('-')[1] == '~') ? '不限制-不限制' : res.ageRange.split('-')[0] == '~' ? '不限制' + '-' + res.ageRange.split('-')[1] : res.ageRange.split('-')[1] == '~' ? res.ageRange.split('-')[0] + '-' + '不限制' : res.ageRange.split('-')[0] + '-' + res.ageRange.split('-')[1]) : '不限制-不限制',
                ageUnit: res.ageRange ? (res.ageRange.split('-')[1] === '~' ? false : true) : ''
            })
            if (res.isOpenWesure) {
                this.insuranceTime()
            }
        })
    },
    // 跳转到支付页面
    async payWage() {
        if (this.data.workerCount > 500) {
            app.alert('员工总数大于500，请使用PC端发薪')
            return
        }
        // if(!user.isOpenPaySalary){
        //     console.log('到这里啦')
        //     this.setData({
        //         isPopupPay:true
        //     })
        //     return
        // }
        const result = await getAccountExpireNotify()
        this.setData({
            expirationTime: result
        })
        if (result.status === 3) {
            this.setData({
                ispopupRemind: true
            })
            return
        } else {
            this.expireCancel()
        }
        // return
        wx.navigateTo({
            url: '/packagePay/pages/pay-wage/pay-wage?id=' + this.data.projectId + '&type=' + this.data.type
        })
    },
    // 获取员工列表
    getProjectWorker() {
        console.log('调用啦吗123')
        if (this.static.notPage) {
            return
        }
        console.log('调用啦吗？？？？？')
        getPayDetailList({
            projectId: this.data.projectId,
            searchText: this.static.searchValue,
            pageSize: 100,
            pageNum: this.static.pageNum,
        }).then(res => {
            this.static.pageNum += 1
            if (!res.hasNextPage) {
                this.static.notPage = true
            }
            for (const i in res.list) {
                res.list[i].userName = res.list[i].workerName
                res.list[i].workerName = res.list[i].workerName + '（' + res.list[i].idCardNo.slice(-4) + '）'
                res.list[i].showAll = false
                res.list[i].key = res.list[i].id + '处理中'
            }
            this.data.workers.push(...res.list)
            this.setData({
                workers: this.data.workers,
                women: res.women,
                men: res.men,
                workerCount: res.count
            })
        })
    },

    getPeople() {
        this.getProjectWorker()
    },

    insuranceTime() {
        // todo: 需要性能优化时，将需要修改的所有数据放入一个数组中，实现一次setData修改整体界面
        setInterval(() => {
            this.data.workers.forEach((item, index) => {
                if (item.countDown === 0) {
                    this.data.workers[index].policyStatus = this.data.workers[index].policyStatus || '处理中'
                    this.data.workers[index].key = this.data.workers[index].id + '处理中'
                    this.data.workers[index].countDown = false
                    confirmInsure({
                        authRecordId: this.data.workers[index].payrollCardRecordId
                    })
                }
                if (item.countDown) {
                    this.data.workers[index].countDown = item.countDown - 1
                }
            })
            this.setData({
                workers: this.data.workers
            })
        }, 1000)
    },
    // 搜索员工
    searchWorker(event) {
        shake(() => {
            this.static.pageNum = 1
            this.static.notPage = false
            this.static.searchValue = event.detail.value
            this.data.workers = []
            this.getProjectWorker()
        }, 800)
    },
    // 显示更多
    showMore(event) {
        console.log(event, 'event')
        const index = event.currentTarget.dataset.index
        const list = [{
            text: '电话',
            key: event.currentTarget.dataset.phone,
            icon: '/assets/img/call.png',
            bind: 'call'
        },
        {
            text: '标记大神',
            key: index,
            icon: '/assets/img/black.png',
            bind: 'mark'
        },
        ]
        if (this.data.isOpenWesure && (this.data.workers[index].policyStatus === '保障中' || this.data.workers[index].policyStatus === '已失效')) {
            list.push({
                text: '查看保单',
                key: index,
                icon: '/assets/img/preview.png',
                bind: 'preview'
            })
        }
        list.push({
            text: '删除',
            key: index,
            icon: '/assets/img/delete.png',
            bind: 'delete'
        })
        this.setData({
            'moreList': list
        })
        this.setData({
            morePosition: event.touches[0].clientY - 30,
            showMoreStatus: true
        })
    },
    // 隐藏显示更多
    hideMore() {
        this.setData({
            showMoreStatus: false
        })
    },
    inputchange(event) {
        inputchange(event, this)
    },


    // 打电话
    call(event) {
        wx.makePhoneCall({
            phoneNumber: event.detail
        })
    },
    // 标记大神
    markGod(event) {
        console.log(this.data.workers)
        this.setData({
            showGodAddStatus: true,
            godBasicMsg: this.data.workers[event.detail]
        })
    },
    // 删除员工
    deleteWorker(event) {
        app.confirm('是否删除该员工?').then(() => {
            deleteWorker({
                id: this.data.workers[event.detail].id
            }).then(() => {
                app.toast('删除成功!', 'success')
                setTimeout(() => {
                    this.static.pageNum = 1
                    this.static.notPage = false
                    this.setData({
                        workers: []
                    })
                    this.getProjectWorker()
                }, 1000)
            })
        })
    },
    // 添加大神成功回调
    addGodComplete() {
        this.static.pageNum = 1
        this.static.notPage = false
        this.getProjectWorker()
        this.setData({
            showGodAddStatus: false,
        })
    },
    // 隐藏添加大神弹窗
    hideGodAdd() {
        this.setData({
            showGodAddStatus: false
        })
    },
    // 显示邀请弹窗
    showInvitation() {
        this.setData({
            invitationStatus: true
        })
    },

    // 隐藏邀请弹窗
    hideInvitation() {
        this.setData({
            invitationStatus: false
        })
    },

    // 前往从通讯录添加员工界面
    addWorkerFromBook() {
        wx.navigateTo({
            url: '/packagePay/pages/book-add/book-add?projectId=' + this.data.projectId + '&companyId=' + this.data.companyId + '&type=pay',
            events: {
                acceptDataFromOpenedPage: (data) => {
                    addToProjectFromBook({
                        projectId: this.data.projectId,
                        serveCompanyId: this.data.companyId,
                        addressBookIds: data.data
                    }).then(() => {
                        console.log(data, 'data')
                        app.toast('添加成功')
                        this.getProjectWorker()
                    })
                },
                dataCallback: (data) => {
                    console.log(data.data)
                    if (data.data == 'payData') {
                        this.setData({
                            workers: []
                        })
                        this.static.notPage = false
                        this.static.pageNum = 1
                        this.getProjectWorker()
                    }
                }
            }
        })
    },
    // 保险邀请员工需要前置定位
    onInsurancePost() {
        if (this.data.isOpenWesure === 0) {
            app.toast('该投保企业已删除，请重新申请，或重新发起保单')
            return
        }
        if (this.data.wesureIsDelete) {
            app.toast('该企业暂不可投保，请在投保企业管理中确认')
            return
        }
        wx.showLoading({
            title: '正在加载中...',
            mask: true,
        })
        getLocation({
            type: 'gcj02',
            isHighAccuracy: true,
        }).then(res => {
            this.setData({
                invitationStatus: false
            })
            wx.navigateTo({
                url: '/packageInsurance/pages/insurance-poster/insurance-poster?projectName=' + this.data.projectName + '&projectId=' + this.data.projectId + '&coord=' + (res.longitude + ',' + res.latitude)
            })
        })
    },

    // 前往邀请码邀请员工界面
    goInvitationCode() {
        this.setData({
            invitationStatus: false
        })
        wx.navigateTo({
            url: '/packagePay/pages/invitation-code/invitation-code?projectName=' + this.data.projectName + '&projectId=' + this.data.projectId
        })
    },
    // 前往二维码邀请管理员界面
    goMasterInvitationQrCode() {
        this.setData({
            invitationStatus: false
        })
        wx.navigateTo({
            url: '/packagePay/pages/master-invitation-qrcode/master-invitation-qrcode?projectId=' + this.data.projectId + '&projectName=' + this.data.projectName
        })
    },
    // 海报邀请员工界面
    goInvitationPoster() {
        wx.navigateTo({
            url: '/packagePay/pages/invitation-poster/invitation-poster?projectName=' + this.data.projectName + '&projectId=' + this.data.projectId
        })
    },
    // 导出名单
    exportWorkerList() {
        newExportWorkerList({
            projectId: this.data.projectId
        }).then(res => {
            const url = app.globalData.baseUrl + '/common/download?fileName=' + res +
                '&delete=false'
            console.log(url)
            if (wx.canIUse('openDocument')) {
                const projectName = this.data.projectName.replace(/\//g, '.') + '.xlsx'
                console.log(projectName, 'projectName')
                openDocument(url, projectName).then(() => {}, () => {
                    this.setData({
                        copyLinkStatus: true,
                        copyLinkContent: url
                    })
                })
            } else {
                this.setData({
                    copyLinkStatus: true,
                    copyLinkContent: url
                })
            }
        })
    },
    // 复制名单下载链接
    copyWorkerListLink() {
        const t = this
        wx.setClipboardData({
            data: this.data.companyName + '\r\n' + this.data.copyLinkContent,
            success() {
                t.setData({
                    copyLinkStatus: false
                })
            }
        })
    },
    // 显示发单政策
    tipPolicy() {
        wx.showModal({
            title: '政策内容',
            content: this.data.billingPolicy,
            showCancel: false,
        })
    },
    // 复制链接
    hideCopyLink() {
        this.setData({
            copyLinkStatus: false
        })
    },
    // 设置打卡地点
    onSelectAddress() {
        wx.navigateTo({
            url: '/packagePay/pages/clock-address/clock-address'
        })
    },
    // 设置打卡地点回调
    selectAddressComplete(data) {
        console.log(data, 'data打卡地点回调')
        setProjectClockAddress({
            signPlace: data.current.name,
            signType: 1,
            signLocation: data.longitude + ',' + data.latitude,
            signRange: data.radius,
            pjId: this.data.projectId
        }).then(() => {
            app.toast('修改成功', 'success')
            this.setData({
                clockAddress: data.current.name,
            })
        })
    },
    // 设置打卡时间
    onSetClockTime() {
        wx.navigateTo({
            url: '/packagePay/pages/clock-time/clock-time'
        })
    },
    setClockTime(startTime, endTime, dayNightFlag) {
        setProjectClockTime({
            signTimeStart: startTime,
            signTimeEnd: endTime,
            dayNightFlag: dayNightFlag,
            projectId: this.data.projectId
        }).then(() => {
            app.toast('修改成功', 'success')
            this.setData({
                clockStartTime: startTime,
                clockEndTime: endTime,
                dayNightFlag
            })
        })
    },
    // 设置押薪天数
    onShowStaffUnderpay() {
        this.setData({
            setStaffUnderpayStatus: true
        })
    },
    // 取消
    cancelSetStaffUnderpay() {
        this.setData({
            setStaffUnderpayStatus: false
        })
    },
    onSetStaffUnderpay() {
        setProjectClockTime({
            staffUnderpay: this.data.setStaffUnderpay,
            projectId: this.data.projectId
        }).then(() => {
            app.toast('修改成功', 'success')
            this.setData({
                staffUnderpay: this.data.setStaffUnderpay,
                setStaffUnderpayStatus: false
            })
        })
    },

    // 前往用户个人信息界面
    onGoWorker(event) {
        console.log(event, 'eventevent')
        if (event.currentTarget.dataset.islogout) {
            toast('该用户已注销')
            return
        }
        const workerId = event.currentTarget.dataset.id
        wx.navigateTo({
            url: '/pages/worker/index/index?id=' + workerId
        })
    },
    onShareAppMessage() {
        return {
            title: user.userName + '邀请您加入「' + (this.data.projectName || user.companyName) + '」' + (this.data.projectName ? '名单管理' : '项目'),
            path: '/pages/index/index?scene=' + encodeURIComponent('uId=' + user.userId + '&cId=' + user.companyId + (this.data.projectId ?
                ('&pId=' + this.data.projectId) : '')),
            imageUrl: '/packagePay/assets/img/resident/share.png'
        }
    },
    tipInsurance(event) {
        console.log(event)
        console.log(event.currentTarget.top)
        this.setData({
            isTipInsurance: true,
            tipTop: event.currentTarget.offsetTop + 20,
            tipLeft: event.detail.x - 10
        })
    },
    cancelTipInsurance() {
        this.setData({
            isTipInsurance: false
        })
    },
    // 取消投保
    onCancelInsure(event) {
        const {
            id,
            index
        } = event.currentTarget.dataset
        let second = ''
        confirm('确认取消投保吗？').then(() => {
            second = this.data.workers[index].countDown
            if (second > 0) {
                cancelInsure({
                    id: id
                }).then(() => {
                    toast('已取消投保')
                    this.setData({
                        ['workers[' + index + '].countDown']: false
                    })
                })
            } else {
                toast('当前已完成投保')
            }
        })


        console.log(id, index, 'event')
    },
    // 下载保单pdf
    previewInsurance(event) {
        getInsurancePdf({
            id: this.data.workers[event.detail].wesureRecordId
        }).then(pdf => {
            if (wx.canIUse('openDocument')) {
                const projectName = this.data.workers[event.detail].workerName + this.data.date + '保单.pdf'
                openDocument(pdf, projectName).then(() => {}, () => {
                    this.setData({
                        copyLinkStatus: true,
                        copyLinkContent: pdf
                    })
                })
            } else {
                this.setData({
                    copyLinkStatus: true,
                    copyLinkContent: pdf
                })
            }
        })
    },
    noGoprojectDetail() {
        console.log('点击啦')
        wx.navigateTo({
            url: '/packagePay/pages/new-resident-detail/new-resident-detail?id=' + this.data.projectId,
        })
    },
    // 去项目导入
    goImportPersonnel() {
        console.log('点击啦')
        wx.navigateTo({
            url: '/packagePay/pages/new-select-list/new-select-list',
        })
    },
    // 忽略发薪
    expireCancel() {
        this.setData({
            ispopupRemind: false
        })
    },
    // 关闭弹窗
    onClose() {
        this.setData({
            isPopupPay: false
        })
    }
})